<?php
require_once("includes/pagetop.php");
include_once("updates/CommonFeatures.php");
include_once("lib/functions.php");
getProjectRootPath();

//include_once ("../updates/PostActions.php");


if(!isset($_SESSION['Allyfolio_User_ID']) || $_SESSION['Allyfolio_User_ID']==0)
{
    redirect("index.php");
}

$logObj=new Log();

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<meta http-equiv="X-UA-Compatible" content="IE=edge" />
	<title>AllyFolio | Messages</title>
	<link href="css/style.css" rel="stylesheet" type="text/css" media="all"  />
	
	<script src="js/general.js"></script>
	<script src="js/functions.js"></script>
	
	<link rel="stylesheet" href="alertify/themes/alertify.core.css" />
	<link rel="stylesheet" href="alertify/themes/alertify.default.css" id="toggleCSS" />
	<script src="alertify/lib/alertify.min.js"></script>	
	<script src="js/jquery1.10.2.min.js"></script>
	
	<script src="js/modernizr.custom.56223.js"></script>
	<style type="text/css">
		.logo{ margin-top:10px;}
	
		textarea select{ border:1px solid #ccc}
		input textarea select{ border:1px solid #999}
		
	</style>
	
	<!-- custom post submission jquery by sujeet -->
	
	<script type="text/javascript" src="js/script.js"></script>
	
	<script src="js/jquery.placeholder.js"></script>
	<script type="text/javascript">
	    $(function() { $('input, textarea').placeholder();});
	</script>
	<script type="text/javascript" src="js/fancybox/jquery.fancybox.js?v=2.1.5"></script> 
	<link rel="stylesheet" type="text/css" href="js/fancybox/jquery.fancybox.css?v=2.1.5" media="screen" /> 
	<style type="text/css">
	    .placeholder {
	      color: #cccccc;
	      }
	</style>
	
	<!-- styles needed by jScrollPane - include in your own sites -->
	<link type="text/css" href="css/jquery.jscrollpane.css" rel="stylesheet" media="all" />
	<style type="text/css" >
		/* Styles specific to this particular page */
		.scroll-pane
		{
			width: 100%;
			height: 500px;
			overflow: auto;
		}
		.horizontal-only
		{
			height: auto;
			max-height: 500px;
		}
		.jspVerticalBar
		{
			display: none;
		}
		.scroll-pane:hover .jspVerticalBar 
		{ 
			display:block; 
		}
	</style>
	<style>
		.delete_box_td
		{
			display: none;
		}
	</style>
	<!-- the mousewheel plugin -->
	<script type="text/javascript" src="js/jquery.mousewheel.js"></script>
	<!-- the jScrollPane script -->
	<script type="text/javascript" src="js/jquery.jscrollpane.min.js"></script>
	<script type="text/javascript" >
		var hasMoreFriends=false;
		var hasMoreMessage=false;
		var isPageLoadedForRight=false;
		var isRightInBottom=false;
		var paneL,paneR;
		var apiL,apiR;
		$(function()
		{
			paneL = $('#Scroll');
			paneL.jScrollPane({
				showArrows: true,
				horizontalGutter: 30,
				arrowScrollOnHover: true,
				autoReinitialise: true
			});
			apiL = paneL.data('jsp');
			paneL.bind(
				'jsp-scroll-y',
				function(event, scrollPositionY, isAtTop, isAtBottom)
				{
					if(isAtBottom && hasMoreFriends)
					{
						displayNextMessagedFriend();
					}
				}
			)
		});
		$(function()
		{
			paneR = $('#ScrollR');
			paneR.jScrollPane({
				showArrows: true,
				horizontalGutter: 30,
				autoReinitialise: true
			});
			apiR = paneR.data('jsp');
			apiR.scrollTo(0, 999);
			paneR.bind(
				'jsp-scroll-y',
				function(event, scrollPositionY, isAtTop, isAtBottom)
				{
					if(isAtTop && hasMoreMessage && isPageLoadedForRight)
					{
						displayPreviousMessages();
					}
					if(!isAtTop)
					{
						isPageLoadedForRight=true;
					}
					if(isAtBottom)
					{
						isRightInBottom=true;
					}
					else
					{
						isRightInBottom=false;
					}
				}
			)
		});
		
		function rightSideScroller()
		{
			apiR.reinitialise();
		}
		function leftSideScroller()
		{
			apiL.reinitialise();
		}
	</script>
</head>

<body>
<?php
$message_status=0; //0 for normal message
if(isset($_REQUEST["type"]))
{
	if(trim($_REQUEST["type"])=="archive")
	{
		$message_status=1;
	}
	else if(trim($_REQUEST["type"])=="spam")
	{
		$message_status=2;
	}
}
try{
	$loginUserID=$_SESSION['Allyfolio_User_ID'];
	
	$qryLoginUserInfo="select * from af_users where User_ID='".$loginUserID."'";
	$arrLoginUserInfo = $pdodbobj->fetch_array($pdodbobj->query($qryLoginUserInfo,array()));
	
	$startFrom=0;
	$totalRecordsPerPage=5;
	
	
    $qryFetchAllMessagedFriends="select af_users.*,tempchat.* from af_users, (select *,if(`from`='".$loginUserID."', `to`, `from`) as friendID from cometchat where (`from`='".$loginUserID."' or `to`='".$loginUserID."') and message_status='".$message_status."' order by sent desc) as tempchat where af_users.User_ID<>'".$loginUserID."'  and ((af_users.User_ID=tempchat.`from` and tempchat.`to`='".$loginUserID."' ) or (af_users.User_ID=tempchat.`to` and tempchat.`from`='".$loginUserID."')) group by af_users.User_ID order by sent desc";
    $arrFetchAllMessagedFriends = $pdodbobj->fetch_array($pdodbobj->query($qryFetchAllMessagedFriends,array()));
    
//    echo "<pre>";
//    print_r($arrFetchAllMessagedFriends);
//    echo "</pre>";
    
    $arrFetchFullMessages=array();
    $recentFriend="0";
    if(count($arrFetchAllMessagedFriends)>0)
    {
		//Fetch first friend chat
		$recentFriend=$arrFetchAllMessagedFriends[0]["User_ID"];
		$qryFetchFullMessages="select * from cometchat where ((`from`='".$loginUserID."' and `to`='".$recentFriend."') or (`to`='".$loginUserID."' and `from`='".$recentFriend."')) and message_status='".$message_status."' order by sent desc limit ".$startFrom.", ".$totalRecordsPerPage;
		$arrFetchFullMessages = $pdodbobj->fetch_array($pdodbobj->query($qryFetchFullMessages,array()));
		
		//make all unread as read
		$qryMakeRead="update cometchat set `read`=1 where `to`='".$loginUserID."' and `from`='".$recentFriend."' and message_status='".$message_status."' ";
		$pdodbobj->query($qryMakeRead,array());
		
		$qryFetchFullMessagesCount="select count(*) as totalRows from cometchat where ((`from`='".$loginUserID."' and `to`='".$recentFriend."') or (`to`='".$loginUserID."' and `from`='".$recentFriend."')) and message_status='".$message_status."' order by sent limit ".$startFrom.", ".$totalRecordsPerPage;
		$arrFetchFullMessagesCount = $pdodbobj->fetch_array($pdodbobj->query($qryFetchFullMessagesCount,array()));
	}
	
	//Get Unread Message Count
	$qryFetchUnreadMessagesCount="select count(*) as unreadcount from cometchat where `to`='".$loginUserID."' and `read`=0 and message_status='0'";
	$arrFetchUnreadMessagesCount = $pdodbobj->fetch_array($pdodbobj->query($qryFetchUnreadMessagesCount,array()));
	
	//Get Archive Message Count
	$qryFetchArchiveMessagesCount="select count(distinct(friendID ))  as unreadcount from (select if(`from`='".$loginUserID."', `to`, `from`) as friendID from cometchat where (`to`='".$loginUserID."' or `from`='".$loginUserID."') and message_status='1' ) as temp";
	
	$arrFetchArchiveMessagesCount = $pdodbobj->fetch_array($pdodbobj->query($qryFetchArchiveMessagesCount,array()));
	
	//Get spam Message Count
	$qryFetchSpamMessagesCount="select count(distinct(friendID ))  as unreadcount from (select if(`from`='".$loginUserID."', `to`, `from`) as friendID from cometchat where (`to`='".$loginUserID."' or `from`='".$loginUserID."') and message_status='2' ) as temp";
	$arrFetchSpamMessagesCount = $pdodbobj->fetch_array($pdodbobj->query($qryFetchSpamMessagesCount,array()));
    
//    echo "<pre>";
//    print_r($arrFetchFullMessages);
//    echo "</pre>";
    
}
catch(Exception $ex){
    $logObj->writeException("home.php Exception: => ".$ex->getMessage());
    die("techno.php fetching user details".$ex->getMessage());
}


function displayFormatedMessage($message, $messageType)
{
	if($messageType=="IMAGE")
	{
		echo '<a href="'.$message.'" class="PagePhotoGallery" data-fancybox-group="PagePhotoGallery"><img src="uploads/image_crop.php?image=/'.$message.'&width=30&height=30&cropratio=30:30" /></a>';
	}
	else if($messageType=="AUDIO" || $messageType=="VIDEO" || $messageType=="DOCUM")
	{
		if($messageType=="DOCUM") 
		{
			$messageType="DOCUMENT";
		}
		echo '<a href="'.$message.'" target="_blank">'.$messageType.'</a>';
	}
	else
	{
		echo $message;
	}
}



?>
	<div id="main_wrapper">
    <!--=================Header Start=======================-->
	<?php include_once("includes/header_right_logo.php") ?>
	<?php include_once("smiley.php");?>
	<script type="text/javascript" src="js/smiley.js"></script>
	<script type="text/javascript" src="js/jquery.autoSuggest.js"></script>
	<link type="text/css" href="css/jquery.autoSuggest.css" rel="stylesheet" media="all" />
    
    <!--=================Header end=======================-->

    <!--=================Body Contain Start=======================-->
    
    <div class="wrapper">
      <div class="header">
        <div class="contain-wrap2 shadow" style=" width:100%; ">
		   
          
      <div class="msg_left" style="margin-top:40px;">
      <?php 
      	if(count($arrFetchAllMessagedFriends)>0)
	    {
	   ?>
	   <script>
	   		var userEmailArr=new Array();
	   </script>
	   	
	   	<table border="0" cellpadding="0" cellspacing="0" >
			<tr>
				<td colspan="3"><input type="text" placeholder="Search here" id="message_search_text" name="message_search_text" class="serch_blue" style="width:318px; float:left; margin-right:5px"><img src="images/srch.png"></td>
				
			</tr>
		</table>
		<div class="scroll-pane" id="Scroll">
			<table id="left_messaged_friend_table" border="0" class="notu" style="text-shadow:none !important; font-weight:bold; border-right:1px solid #3CAFE4">	
			<?php
				$leftMesasgedFriend=0;
				
//				echo "<pre>";
//				print_r($arrFetchAllMessagedFriends);
//				echo "</pre>";
				
				for($i=0; $i<count($arrFetchAllMessagedFriends) && $i<$totalRecordsPerPage; $i++)
				{
					//check All Read or not
					$qryCheckAllRead="select count(*) as unreadCount from cometchat where `to`='".$loginUserID."' and `from`='".$arrFetchAllMessagedFriends[$i]["friendID"]."' and `read`=0 and message_status='".$message_status."'";
					$arrCheckAllRead = $pdodbobj->fetch_array($pdodbobj->query($qryCheckAllRead,array()));
					
					$leftMesasgedFriend++;
					$sentDate=getTimeAgo($arrFetchAllMessagedFriends[$i]["sent"], time());
			?>
				<script>
			   		userEmailArr['<?php echo $arrFetchAllMessagedFriends[$i]["User_ID"]; ?>']="<?php echo $arrFetchAllMessagedFriends[$i]["Allyfolio_User_ID"]; ?>";
			   </script>
				<tr <?php if($arrCheckAllRead[0]["unreadCount"]>0){ ?>style="background: #EEE;"<?php } ?> id="left_messaged_friend_tr_<?php echo $arrFetchAllMessagedFriends[$i]["User_ID"]; ?>" onclick="displayFullMessage('<?php echo $arrFetchAllMessagedFriends[$i]["User_ID"]; ?>');" >
				<?php
					if($i%2==0)
					{
				?>
					<td width="62" style="padding:0px;">
						<div class="noti_pic"><a href="javascript:void(0);"><img src="<?php echo "uploads/image_crop.php?image=/".$arrFetchAllMessagedFriends[$i]["Profile_Pic_Path"]."&width=48&height=45&cropratio=48:45";  ?>" /></a></div>
					</td>
					<td width="319" valign="top" style="text-align:left;">
						<div style="position:relative; top:0px"><a href="javascript:void(0);"><span class="noti_name" style="margin-top:5px;"><?php echo $arrFetchAllMessagedFriends[$i]["Full_Name"] ?></span></a></div>
						<div class="separator"></div>
						<span style="margin-top:10px; float:left; margin-right:5px;">
						<?php 
							displayFormatedMessage($arrFetchAllMessagedFriends[$i]["message"],$arrFetchAllMessagedFriends[$i]["message_type"]);
						?>
						</span>
					</td>
					<td width="77" align="right" valign="top">
						<span style="margin-top:5px; float:right; margin-right:5px;"><?php echo $sentDate; ?></span>
					</td>
				<?php		
					}
					else
					{
				?>
					<td width="77" align="right" valign="top">
						<span style="margin-top:5px; float:left; margin-right:5px;"><?php echo $sentDate; ?></span>
					</td>
					<td width="319" valign="top" style="text-align:right;">
						<div style="position:relative; top:0px"><a href="javascript:void(0);"><span class="noti_name" style="margin-top:5px;"><?php echo $arrFetchAllMessagedFriends[$i]["Full_Name"] ?></span></a></div>
						<div class="separator"></div>
						<span style="margin-top:10px; float:right; margin-right:5px;">
						<?php 
							displayFormatedMessage($arrFetchAllMessagedFriends[$i]["message"],$arrFetchAllMessagedFriends[$i]["message_type"]);
						?>
						</span>
					</td>
					<td width="62" style="padding:0px;">
						<div class="noti_pic"><a href="javascript:void(0);"><img src="<?php echo "uploads/image_crop.php?image=/".$arrFetchAllMessagedFriends[$i]["Profile_Pic_Path"]."&width=48&height=45&cropratio=48:45";  ?>" /></a></div>
					</td>
				<?php		
					}
				?>	
				</tr>
		<?php		
			}
			?>
			</table>
		</div>	
		<table border="0" cellpadding="0" cellspacing="0">
			<?php
			if(count($arrFetchAllMessagedFriends)>$totalRecordsPerPage)
			{
		?>
			<!--<tr id="left_messaged_friend_more_tr">
				<td colspan="3"><div style="margin-top:327px !important; width:100%; text-align:center !important; color:#4ca1d4;"><a href="javascript:void(0);" onclick="return displayNextMessagedFriend();">More...</a></div></td>
			</tr>-->
			<script>
				hasMoreFriends=true;
			</script>
		<?php
			}
		?>	
		</table>
	   <?php 	
		}
		else
		{
			echo "You have no messages.";
		}	
      ?>
	  	
	  </div>
	  <div class="msg_right" style="overflow-y:auto;">
	  	<div id="image_loader_div" style="display:none;"><img src="images/LoadingBar.gif" width="64px" height="64px"/></div>
	  	
	  
		<table border="0" cellpadding="0" cellspacing="0">
			<tr>
				<td colspan="3" align="center">
					<div style="width:49%; text-align:center; float:left; font-size:30px; position:relative">
						Inbox (<span id="inbox_message_count_span"><?php echo $arrFetchUnreadMessagesCount[0]["unreadcount"]; ?></span>)<img src="images/downaa.png" onclick="return showHide();" style="cursor:pointer" />
						<div style="position:absolute; padding:5px; border:1px solid #abe1fa; background:#fff; z-index:999; left:119px; display:none" id="showHideDiv" >
							<ul style="padding:0; margin:0; font-size:12px;list-style:none" class="drop">
								<li style="padding:2px 0;"><a href="messages.php?type=inbox"><span>Unread</span><span style="float:right;" id="unread_message_count_span"><?php echo $arrFetchUnreadMessagesCount[0]["unreadcount"]; ?></span></a></li>
								<li style="padding:2px 0;"><a href="messages.php?type=spam"><span>Spam</span><span style="float:right;" id="spam_message_count_span"><?php echo $arrFetchSpamMessagesCount[0]["unreadcount"]; ?></span></a></li>
								<li style="padding:2px 0;"><a href="messages.php?type=archive"><span>Archive</span><span style="float:right;" id="archive_message_count_span"><?php echo $arrFetchArchiveMessagesCount[0]["unreadcount"]; ?></span></a></li>
							</ul>
						</div>
					</div>
					<div style="width:49%; text-align:center; float:right ;font-size:30px; position:relative;<?php if(count($arrFetchFullMessages)<1){ echo "display:none";} ?>" id="actions_div">
						Actions<img src="images/downaa.png" onclick="return showHide1();" style="cursor:pointer" />
						<div style="position:absolute; padding:5px; border:1px solid #abe1fa; background:#fff; z-index:999; left:119px; display:none" id="showHideDiva">
							<ul style="padding:0; margin:0; font-size:12px;list-style:none" class="drop">
								<li style="padding:2px 0;"><span><a href="javascript:void(0);" onclick="return displayProfile();">View profile</a></span></li>
								<li style="padding:2px 0;"><span><a href="javascript:void(0);" onclick="return displayChatBox();">Open in chat</a></span></li>
								<li style="padding:2px 0;"><span><a href="javascript:void(0);" onclick="return showDeleteFeature();">Delete messages</a></span></li>
								<li style="padding:2px 0;"><span><a href="javascript:void(0);" onclick="return archiveSpamMessage(3);">Delete conversion</a></span></li>
							<?php
								if(!isset($_REQUEST["type"]) || trim($_REQUEST["type"])!="archive")
								{
							?>
								<li style="padding:2px 0;"><span><a href="javascript:void(0);" onclick="return archiveSpamMessage(1);">Archive</a></span></li>
							<?php		
								}
							?>
							<?php
								if(isset($_REQUEST["type"]) && trim($_REQUEST["type"])!="inbox")
								{
							?>	
								<li style="padding:2px 0;"><span><a href="javascript:void(0);" onclick="return archiveSpamMessage('0');">Move to Inbox</a></span></li>
							<?php
								}
							?>	
								<li style="padding:2px 0;"><span><a href="javascript:void(0);" onclick="return markAsReadUnread('1');">Mark as read</a></span></li>
								<li style="padding:2px 0;"><span><a href="javascript:void(0);" onclick="return markAsReadUnread('0');">Mark as unread</a></span></li>
							<?php
								if(!isset($_REQUEST["type"]) || trim($_REQUEST["type"])!="spam")
								{
							?>
								<li style="padding:2px 0;"><span><a href="javascript:void(0);" onclick="return archiveSpamMessage(2);">Report spam or abuse</a></span></li>
							<?php		
								}
							?>	
							</ul>
						</div>
					</div>
				</td>
			</tr>
			<?php 
				if($arrFetchFullMessagesCount[0]["totalRows"]>$totalRecordsPerPage) 
				{ 
			?>
				<script>
					hasMoreMessage=true;
				</script>
			<?php 
				} 
			?>
			<!--<tr id="right_full_message_more_tr" style="display:block;">
				<td colspan="3"><div style=" width:100%; text-align:center !important; color:#4ca1d4;"><a href="javascript:void(0);" onclick="return displayPreviousMessages();">More...</a></div></td>
			</tr>-->
		</table>
		<div id="ScrollR" class="scroll-pane">	
			<table id="right_side_message_table" border="0" class="notu" style="text-shadow:none !important; font-weight:bold;" width="100%" cellpadding="0" cellspacing="0">
	<?php
		//echo "<pre>";
//		print_r($arrFetchFullMessages);
//		echo "</pre>";
		
	  	if(count($arrFetchFullMessages)>0)
	  	{
			$lastMessageID="";
			$firstMessageID=$arrFetchFullMessages[0]["id"];
			for($j=(count($arrFetchFullMessages)-1); $j>=0; $j--)
			{
				if($lastMessageID=="")
				{
					$lastMessageID=$arrFetchFullMessages[$j]["id"];
				}
				$sentMsgDate=getTimeAgo($arrFetchFullMessages[$j]["sent"], time());
		?>
			<tr class="right_side_message_tr">
			<?php
				if($arrFetchFullMessages[$j]["from"]!=$loginUserID)
				{
			?>
				<td class="delete_box_td" >
					<input type="checkbox" id="delete_box_checkbox_<?php echo $arrFetchFullMessages[$j]["id"]; ?>" name="delete_box_checkbox[]" class="delete_box_checkbox" value="<?php echo $arrFetchFullMessages[$j]["id"]; ?>" />
				</td>
				<td width="62" style="padding:0px;">
					<div class="noti_pic">
						<a href="javascript:void(0);"><img src="<?php echo "uploads/image_crop.php?image=/".$arrFetchAllMessagedFriends[0]["Profile_Pic_Path"]."&width=48&height=45&cropratio=48:45";  ?>" /></a>
					</div>
				</td>
				<td width="319" valign="top" style="text-align:left;">
					<div style="position:relative; top:0px"><span class="noti_name" style="margin-top:5px;"><a href="javascript:void(0)"><?php echo $arrFetchAllMessagedFriends[0]["Full_Name"] ?></a></span></div>
					<div class="separator"></div>
					<span style="margin-top:10px; float:left; margin-right:5px;">
					<?php 
						displayFormatedMessage($arrFetchFullMessages[$j]["message"],$arrFetchFullMessages[$j]["message_type"]);
					?>
					</span>
				</td>
				<td width="77" align="right" valign="top">
					<span style="margin-top:5px; float:right; margin-right:5px;"><?php echo $sentMsgDate; ?></span>
				</td>
			<?php		
				}
				else
				{
			?>
				<td width="77" align="right" valign="top">
					<span style="margin-top:5px; float:left; margin-right:5px;"><?php echo $sentMsgDate; ?></span>
				</td>
				<td width="319" valign="top" style="text-align:right;">
					<div style="position:relative; top:0px"><span class="noti_name" style="margin-top:5px;"><a href="javascript:void(0);"><?php echo $arrLoginUserInfo[0]["Full_Name"] ?></a></span></div>
					<div class="separator"></div>
					<span style="margin-top:10px; float:right; margin-right:5px;">
					<?php 
						displayFormatedMessage($arrFetchFullMessages[$j]["message"],$arrFetchFullMessages[$j]["message_type"]);
					?>
					</span>
				</td>
				<td width="62" style="padding:0px;">
					<div class="noti_pic"><a href="javascript:void(0);"><img src="<?php echo "uploads/image_crop.php?image=/".$arrLoginUserInfo[0]["Profile_Pic_Path"]."&width=48&height=45&cropratio=48:45";  ?>" /></a></div>
				</td>
				<td class="delete_box_td" width="8" >
					<input type="checkbox" class="delete_box_checkbox" id="delete_box_checkbox_<?php echo $arrFetchFullMessages[$j]["id"]; ?>" name="delete_box_checkbox[]" value="<?php echo $arrFetchFullMessages[$j]["id"]; ?>" />
				</td>
			<?php		
				}
			?>	
			</tr>
		<?php		
			}		
		}
	  ?>
		</table>
	  </div>
	
	  	<table border="0" cellpadding="0" cellspacing="0" style="<?php if(count($arrFetchFullMessages)<1){ echo "display:none";} ?>">
	  		<tr id="right_side_reply_tr">
				<td colspan="3">
					<form name="send_reply_form" id="send_reply_form"  enctype="multipart/form-data"  action="" method="post" onSubmit="return checkValidation();">
						<div style="width:100%; text-align:left !important; color:#afe2fa; font-size:42px; padding:20px 0; border:1px solid #abe1fa; border-left:none ">
							
							<textarea name="send_message_textarea" id="send_message_textarea" rows="4" cols="75"></textarea>
						</div>
						<ul class="add">
							<li>
								<a href="javascript:void(0);" onclick="return openFile('file_file');">Add File</a>
								<input type="file" id="file_file" name="file_file" style="display:none;" onchange="return uploadMediaInMessage('file');" />
							</li>
							<li>
								<a href="javascript:void(0);" onclick="return openFile('photo_file');">Add Photo</a>
								<input type="file" id="photo_file" name="photo_file" style="display:none;"  accept="image/*"  onchange="return uploadMediaInMessage('photo');" />
							</li>
							<li>
								<a href="javascript:void(0);" onclick="return displaySmileyDiv('reply_smily_div');" title="Smiley">Smily</a>
							</li>
							<li style="width:29%">
								<a href="javascript:void(0);" onclick="return openFile('voice_file');">Voice Message</a>
								<input type="file" id="voice_file" name="voice_file" style="display:none;"  accept="audio/*"  onchange="return uploadMediaInMessage('voice');" />
							</li>
							<div style="clear:both"></div>
						</ul>
						<input type="submit" class="reply" value="Reply"/>
						<div id="reply_smily_div" style="display:none"><?php echo getSmileyText(); ?><a href="javascript:void(0);" onclick="javascript: $('#reply_smily_div').hide();"><img src="images/closeBtn.png" alt="close" /></a></div>
						<div id="send_reply_image_loader_div" style="display:none;"><img src="images/LoadingBar.gif" width="64px" height="64px"/></div>
					</form>
				</td>
			</tr>
			<tr id="right_side_delete_tr" style="display:none;">
				<td colspan="3" align="right">
					<input type="button" value="Cancel" style="width:100px!important" onclick="return hideDeleteFeature();">&nbsp;
					<input type="button" value="Delete" style="width:100px!important" onclick="return deleteMessages();">
				</td>
			</tr>
		</table>
	  </div>    
</div>

    </div>
    
    <div class="clearfix"></div>
    <!--=================Body Contain end=======================-->
	
    </div>
    <div class="clearfix"></div>
    </div>
    
         
<?php
    require_once("includes/footer.php");
?>
<script type="text/javascript" language="javascript">// <![CDATA[
function showHide() {
    var ele = document.getElementById("showHideDiv");
    if(ele.style.display == "block") {
            ele.style.display = "none";
      }
    else {
        ele.style.display = "block";
    }
}

function showHide1() {
    var ele = document.getElementById("showHideDiva");
    if(ele.style.display == "block") {
            ele.style.display = "none";
      }
    else {
        ele.style.display = "block";
    }
}
// ]]></script>
<script lang="javascript">
//<![CDATA[

//$(".delete_box_checkbox").hide();

function hideDeleteFeature()
{
	$(".delete_box_td").css("display","none");
	$("#right_side_delete_tr").hide();
	$("#right_side_reply_tr").show();
}
function showDeleteFeature()
{
	$(".delete_box_td").css("display","block");
	$(".delete_box_td").show();
	$("#right_side_delete_tr").show();
	$("#right_side_reply_tr").hide();
}

function deleteMessages()
{
	var deleteMessageIds=""
	$(".delete_box_checkbox").each(function(){
		if($(this).is(":checked"))
		{
			deleteMessageIds +=$(this).attr("value")+",";
		}
	});
	if(deleteMessageIds!="")
	{
		deleteMessageIds=deleteMessageIds.substr(0,(deleteMessageIds.length-1));
		document.getElementById("image_loader_div").style.display="";
		$.ajax({
	      cache:false,  
	      async:false,
		  url: "ajax_message.php?action=archiveOrSpamMessages&currentFriendInRightSide="+currentFriendInRightSide+"&actionType=3&message_status=<?php echo $message_status; ?>&deleteMessageIds="+deleteMessageIds,
		  success: function( data ) {
		    
	        var dataarr=data.split("|~|~|");
	        if(dataarr[0]=="SUCCESS")
	        {
	            $("#left_messaged_friend_table").html(dataarr[1]);
	            currentFriendsCountInLeft=dataarr[2];
	            
	            if(currentFriendsCountInLeft==totalMessagedFriends)
	            {
					hasMoreFriends=false;
				}
				leftSideScroller();
				if(dataarr[3]>0)
				{
					displayFullMessage(dataarr[3]);
				}
				else
				{
					//Blank right side
					$("#ScrollR").html("");
					$("#actions_div").html("");
					$("#right_side_reply_tr").html('<td colspan="3"></td>');
				}	
	        }
	        else
	        {
	            alertify.alert(dataarr[1]);
	        }
	        document.getElementById("image_loader_div").style.display="none";
	        return false;
		  },
		  error: function(data)
		  	{
				alertify.alert("Looks like there is some problem. Please try after some time.");
			}
		});
	}
	else
	{
		alertify.alert("Please select atleast one message");
	}
}

$("#message_search_text").autoSuggest(
	"ajax_message_search.php", 
	{
		minChars: 2,
		extraParams:"&message_status=<?php echo $message_status; ?>",
		selectionLimit:1,
		selectedItemProp:"name",
		searchObjProps:"name",
		asHtmlID:"aaa",
		resultClick: function(data){ 
			var selectedID =$("#as-values-aaa").val();
			selectedID=selectedID.replace(/,/g, "");
			displayFullMessage(selectedID);
		}
	}
);
function displaySmileyDiv(divID)
{
	$("#"+divID).show();
}

function uploadMediaInMessage(messageType)
{
	fileControlId=messageType+"_file";
	if(document.getElementById(fileControlId).value!="")
	{
		document.getElementById("send_reply_image_loader_div").style.display="";
		formdata = false;
		if (window.FormData) {
			formdata = new FormData(document.getElementById("send_reply_form"));
		}
		var xmlhttp;
		if (window.XMLHttpRequest)
		{// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp=new XMLHttpRequest();
		}
		else
		{// code for IE6, IE5
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{	
				var res=xmlhttp.responseText;	
				dataarr=res.split("|~|~|");
				if(dataarr[0]=="SUCCESS")
				{
					$("#right_side_message_table").append(dataarr[1]);
	            	firstMessageID=dataarr[2];
					document.getElementById("send_reply_image_loader_div").style.display="none";
					rightSideScroller();
				}
				else
				{
					document.getElementById("send_reply_image_loader_div").style.display="none";
					alertify.alert(dataarr[1]);
				}
			}
		}	
		xmlhttp.open("POST","ajax_message.php?action=uploadMediaMessage&messageType="+messageType+"&otheruserid="+currentFriendInRightSide+"&firstmessageid="+firstMessageID+"&message_status=<?php echo $message_status; ?>",true);
		xmlhttp.send(formdata);
	}
}

function openFile(fileControlId)
{
	$("#"+fileControlId).trigger("click");
}

setInterval(autoRefreshMessage, 18000);
function autoRefreshMessage()
{
	$.ajax({
		type: "POST",
		cache: false,
		data: 'action=refreshMessages'+"&otheruserid="+currentFriendInRightSide+"&firstmessageid="+firstMessageID+"&message_status=<?php echo $message_status; ?>",
		url: "ajax_message.php",
		success: function( data ) {
    
	        var dataarr=data.split("|~|~|");
	        if(dataarr[0]=="SUCCESS")
	        {
	            $("#right_side_message_table").append(dataarr[1]);
	            firstMessageID=dataarr[2];
	            rightSideScroller();
	        }
	        else
	        {
	            alertify.alert(dataarr[1]);
	        }
	        return false;
		  },
		  error: function(data)
	  		{
				//document.getElementById("send_reply_image_loader_div").style.display="none";
				alertify.alert("Looks like there is some problem. Please try after some time.");
			}
	});
}

$('#send_message_textarea').keydown(function(event) {
    if (event.keyCode == 13) {
        $(this.form).submit()
        return false;
     }
});

var firstMessageID='<?php echo $firstMessageID; ?>';
function checkValidation()
{
	var errors = [];
	if($('#send_message_textarea').val().trim()=="")
	{
		alertify.alert("Please enter message."); 
	}
	else
	{
		document.getElementById("send_reply_image_loader_div").style.display="";
		$.ajax({
			type: "POST",
			cache: false,
			data: 'action=sendMessages&message='+$('#send_message_textarea').val().trim()+"&otheruserid="+currentFriendInRightSide+"&firstmessageid="+firstMessageID+"&message_status=<?php echo $message_status; ?>",
			url: "ajax_message.php",
			success: function( data ) {
	    
		        var dataarr=data.split("|~|~|");
		        if(dataarr[0]=="SUCCESS")
		        {
		            $("#right_side_message_table").append(dataarr[1]);
		            firstMessageID=dataarr[2];
		            if(isRightInBottom)
		            {
		            	apiR.scrollTo(0, 0);
					}
		        }
		        else
		        {
		            alertify.alert(dataarr[1]);
		        }
		        document.getElementById("send_reply_image_loader_div").style.display="none";
				document.getElementById("send_message_textarea").value="";
		        return false;
			  },
			  error: function(data)
		  		{
				document.getElementById("send_reply_image_loader_div").style.display="none";
				alertify.alert("Looks like there is some problem. Please try after some time.");
				}
		});
	}
    return false;
}

var lastMessageID='<?php echo $lastMessageID; ?>';
function displayPreviousMessages()
{
	isPageLoadedForRight=false;
	document.getElementById("image_loader_div").style.display="";
	$.ajax({
      cache:false,  
      async:false,
	  url: "ajax_message.php?action=getPreviousMessages&lastMessageID="+lastMessageID+"&friendId="+currentFriendInRightSide+"&message_status=<?php echo $message_status; ?>",
	  success: function( data ) {
	    
        var dataarr=data.split("|~|~|");
        if(dataarr[0]=="SUCCESS")
        {
        	
            $("#right_side_message_table tr:first").before(dataarr[1]);
            lastMessageID=dataarr[2];
            if(dataarr[3]=="YES")
            {
				hasMoreMessage=true;
			}
			else
			{
				hasMoreMessage=false;
			}
			rightSideScroller();
        }
        else
        {
            alertify.alert(dataarr[1]);
        }
        document.getElementById("image_loader_div").style.display="none";
        return false;
	  },
	  error: function(data)
	  	{
			document.getElementById("image_loader_div").style.display="none";
			alertify.alert("Looks like there is some problem. Please try after some time.");
		}
	});
}

var currentFriendInRightSide="<?php echo $recentFriend; ; ?>";
function displayFullMessage(friendId)
{
	if(currentFriendInRightSide!="0" && currentFriendInRightSide!=friendId)
	{
		document.getElementById("image_loader_div").style.display="";
		$.ajax({
	      cache:false,  
	      async:false,
		  url: "ajax_message.php?action=getFullMessage&friendId="+friendId+"&message_status=<?php echo $message_status; ?>",
		  success: function( data ) {
		    
	        var dataarr=data.split("|~|~|");
	        if(dataarr[0]=="SUCCESS")
	        {
	        	$(".right_side_message_tr").remove();
	            $("#right_side_message_table").html(dataarr[1]);
	            $("#left_messaged_friend_tr_"+friendId).css("background", "none");
	            currentFriendInRightSide=friendId;
	            lastMessageID=dataarr[2];
	            if(dataarr[3]=="YES")
	            {
					hasMoreMessage=true;
				}
				else
				{
					hasMoreMessage=false;
				}
				$("#unread_message_count_span").html(dataarr[4]);
				rightSideScroller();
	        }
	        else
	        {
	            alertify.alert(dataarr[1]);
	        }
	        document.getElementById("image_loader_div").style.display="none";
	        return false;
		  },
		  error: function(data)
		  	{
				document.getElementById("image_loader_div").style.display="none";
				alertify.alert("Looks like there is some problem. Please try after some time.");
			}
		});
	}
}

var currentFriendsCountInLeft='<?php echo $leftMesasgedFriend; ?>';
var totalMessagedFriends='<?php echo count($arrFetchAllMessagedFriends); ?>';
function displayNextMessagedFriend()
{
	$.ajax({
      cache:false,  
      async:false,
	  url: "ajax_message.php?action=getNextMessagedFriend&currentFriendsCountInLeft="+currentFriendsCountInLeft+"&message_status=<?php echo $message_status; ?>",
	  success: function( data ) {
	    
        var dataarr=data.split("|~|~|");
        if(dataarr[0]=="SUCCESS")
        {
            $("#left_messaged_friend_table").append(dataarr[1]);
            currentFriendsCountInLeft=dataarr[2];
            
            if(currentFriendsCountInLeft==totalMessagedFriends)
            {
				//$("#left_messaged_friend_more_tr").html("<td colspan=\"3\"></td>")
				hasMoreFriends=false;
			}
			leftSideScroller();
        }
        else
        {
            alertify.alert(dataarr[1]);
        }
        return false;
	  },
	  error: function(data)
	  	{
			alertify.alert("Looks like there is some problem. Please try after some time.");
		}
	});
}

$(document).ready(function(){
	$('.PagePhotoGallery').fancybox();
});

function displayProfile()
{
	if(currentFriendInRightSide>0)
	{
		if(userEmailArr[currentFriendInRightSide]!="")
		{
			window.location.href="dna.php?t="+userEmailArr[currentFriendInRightSide];
		}
		else
		{
			alertify.alert("Looks like there is some problem. Please try after some time.");
		}
	}
	return false;
}

function displayChatBox()
{
	//alert(userid);
	if(currentFriendInRightSide>0)
	{
		jqcc.cometchat.chatWith(currentFriendInRightSide);
	}
	return false;
}

function markAsReadUnread(readUnreadValue)
{
	document.getElementById("image_loader_div").style.display="";
	$.ajax({
      cache:false,  
      async:false,
	  url: "ajax_message.php?action=setReadUnread&currentFriendInRightSide="+currentFriendInRightSide+"&readUnreadValue="+readUnreadValue+"&message_status=<?php echo $message_status; ?>",
	  success: function( data ) {
	    
        var dataarr=data.split("|~|~|");
        if(dataarr[0]=="SUCCESS")
        {
            if(readUnreadValue!="1")
            {
				$("#left_messaged_friend_tr_"+currentFriendInRightSide).css("background", "#EEE");
			}
			else
			{
				$("#left_messaged_friend_tr_"+currentFriendInRightSide).css("background", "none");
			}
			$("#unread_message_count_span").html(dataarr[1]);
        }
        else
        {
            alertify.alert(dataarr[1]);
        }
        document.getElementById("image_loader_div").style.display="none";
        return false;
	  },
	  error: function(data)
	  	{
			alertify.alert("Looks like there is some problem. Please try after some time.");
		}
	});
}

function archiveSpamMessage(actionType)
{
	document.getElementById("image_loader_div").style.display="";
	$.ajax({
      cache:false,  
      async:false,
	  url: "ajax_message.php?action=archiveOrSpamMessages&currentFriendInRightSide="+currentFriendInRightSide+"&actionType="+actionType+"&message_status=<?php echo $message_status; ?>",
	  success: function( data ) {
	    
        var dataarr=data.split("|~|~|");
        if(dataarr[0]=="SUCCESS")
        {
            $("#left_messaged_friend_table").html(dataarr[1]);
            currentFriendsCountInLeft=dataarr[2];
            
            if(currentFriendsCountInLeft==totalMessagedFriends)
            {
				hasMoreFriends=false;
			}
			leftSideScroller();
			if(dataarr[3]>0)
			{
				displayFullMessage(dataarr[3]);
			}
			else
			{
				//Blank right side
				$("#ScrollR").html("");
				$("#actions_div").html("");
				$("#right_side_reply_tr").html('<td colspan="3"></td>');
			}	
        }
        else
        {
            alertify.alert(dataarr[1]);
        }
        document.getElementById("image_loader_div").style.display="none";
        return false;
	  },
	  error: function(data)
	  	{
			alertify.alert("Looks like there is some problem. Please try after some time.");
		}
	});
}

<?php
if(isset($msg_success) && $msg_success!="")
{
    ?>
    alertify.alert("<?php echo $msg_success; ?>");
    <?php
}

if(isset($msg_error) && $msg_error!="")
{
    ?>
    alertify.alert("<?php echo $msg_error; ?>");
    <?php
}
?>

//]]>
</script>